import socket
import time

HOST = '0.0.0.0'  # 监听所有接口
PORT = 12345      # 监听端口

def tcp_server():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((HOST, PORT))
        s.listen()
        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] TCP服务器已启动，监听 {PORT} 端口...")
        
        while True:
            try:
                conn, addr = s.accept()
                print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 客户端连接: {addr}")
                
                with conn:
                    while True:
                        try:
                            data = conn.recv(1024)
                            if not data:
                                break
                            print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 收到来自 {addr} 的数据: {data.decode()}")
                            conn.sendall(b'Server received: ' + data)
                        except ConnectionResetError:
                            print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 客户端 {addr} 异常断开")
                            break
                            
                print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 客户端 {addr} 正常断开连接")
                
            except KeyboardInterrupt:
                print(f"\n[{time.strftime('%Y-%m-%d %H:%M:%S')}] 服务器关闭")
                break
            except Exception as e:
                print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 发生错误: {str(e)}")
                continue

if __name__ == '__main__':
    tcp_server()